<template>
  <PublicPage>
    <view class="mx-9">
      <view class="text-center py-14">
        <image
          src="@/static/image/img/logo.png"
          class="w-[352rpx] h-auto"
          mode="widthFix" />
      </view>

      <u-form
        labelPosition="left"
        :model="formData"
        :rules="rules"
        ref="form"
        errorType="border-bottom">
        <u-form-item prop="username" borderBottom>
          <up-input
            v-model="formData.username"
            border="none"
            prefixIcon="search"
            clearable
            placeholder="请输入账号">
            <template #prefix>
              <i class="iconfont u-tips-color text-xl pr-2">&#xe600;</i>
            </template>
          </up-input>
        </u-form-item>
        <view class="py-1"></view>
        <u-form-item prop="password" borderBottom>
          <up-input
            v-model="formData.password"
            border="none"
            prefixIcon="search"
            clearable
            type="password"
            placeholder="请输入密码">
            <template #prefix>
              <i class="iconfont u-tips-color text-xl pr-2">&#xe635;</i>
            </template>
          </up-input>
        </u-form-item>
        <view class="mt-[100rpx]">
          <u-button type="primary" size="large" @click="register">
            <text class="text-base">登 录</text>
          </u-button>
        </view>
      </u-form>

      <!-- <view class="pt-3 u-tips-color text-center absolute bottom-10 w-full left-0">
        <text>登录代表您同意</text>
        <text class="u-primary px-1">用户协议</text>
        <text>和</text>
        <text class="u-primary px-1">隐私条款</text>
      </view> -->
    </view>
  </PublicPage>
</template>

<script setup lang="ts">
import { LoginFormTypes, OnLoadOptions } from '@/types/login'
import { registerLogin } from '@/api/login'
import { reactive } from 'vue'
import { useUserStore } from '@/stores/user'

const formData = reactive<LoginFormTypes>({
  username: '',
  password: '',
  checkbox: false
})

const rules = ref({
  username: {
    type: 'string',
    required: true,
    message: '请输入账号',
    trigger: 'blur'
  },
  password: {
    type: 'string',
    required: true,
    message: '请输入密码',
    trigger: 'blur'
  }
})

const { getUserInfo } = useUserStore()
const callBackPage = ref<string>()

onLoad((options) => {
  // 接收回调页面路径
  callBackPage.value = options?.callBackPage ?? `/pages/index/index`
})

const _that = getCurrentInstance()
const register = async () => {
  (_that?.refs.form as any).validate().then(async() => {
    const data = await registerLogin(formData)
    uni.setStorageSync('token', data.token);
    getUserInfo()

    // 登录成功跳转页面
    uni.$u.route({
      type: 'redirectTo',
      url: unref(callBackPage)
    })
  }).catch((err: any) => {
    uni.showToast({
      title: err[0].message,
      icon: "none"
    });
  });
}
</script>
